﻿using System.IO;
using Microsoft.Xna.Framework.Graphics;

namespace Ultima.Xna.Data
{
    public class TextureMaps
    {
        private static Texture2D[] _cache = new Texture2D[0x4000];
        private static FileIndex _index = new FileIndex("Texidx.mul", "Texmaps.mul", 0x1000, 10);

        public static Texture2D GetTexture(int index, GraphicsDevice graphicsDevice)
        {
            Texture2D texture = _cache[index];

            if (texture == null)
            {
                _cache[index] = texture = Create(index, graphicsDevice);
            }

            return texture;
        }

        private static unsafe Texture2D Create(int index, GraphicsDevice graphicsDevice)
        {
            int extra;
            int length;
            bool patched;

            _index.Seek(index, out length, out extra, out patched);

            extra = extra == 0 ? 64 : 128;

            ushort[] data = new ushort[extra * extra];

            using (BinaryReader reader = new BinaryReader(_index.Stream))
            {
                fixed (ushort* pData = data)
                {
                    ushort* pDataRef = pData;

                    for (int y = 0; y < extra; ++y, pDataRef += extra)
                    {
                        ushort* start = pDataRef;
                        ushort* end = start + extra;

                        while (start < end)
                        {
                            *start++ = (ushort)(reader.ReadUInt16() ^ 0x8000);
                        }
                    }
                }
            }

            Texture2D texture = new Texture2D(graphicsDevice, extra, extra, 1, TextureUsage.None, SurfaceFormat.Bgra5551);

            texture.SetData<ushort>(data);

            return texture;
        }
    }
}